package com.jeeplus.modules.monitor.task;

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.common.utils.io.FileUtil;
import com.jeeplus.modules.monitor.entity.ScheduleJob;
import com.jeeplus.modules.monitor.entity.Task;
import com.jeeplus.modules.tools.utils.MultiDBUtils;
import com.jeeplus.modules.tools.utils.SpringUtil;
import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @title: 生成畅享数据文件
 * @projectName LIUHUAN
 * @description: TODO
 * @date 2019/8/279:25
 */
@DisallowConcurrentExecution
public class TaskVssGenerateDataFile extends Task {
    /*日志*/
    protected Logger logger = LoggerFactory.getLogger(getClass());
    /*DB连接*/
    protected JdbcTemplate jdbcTemplate = (JdbcTemplate) SpringUtil.getApplicationContext().getBean("db") ;
    protected JdbcTemplate jdbcTemplateVss = (JdbcTemplate) SpringUtil.getApplicationContext().getBean("db") ;
    protected String rcvPath = "d:\\VSSRCV\\";

    @Override
    public void run(ScheduleJob scheduleJob) {
        try {
            List<Map<String, Object>> dataTable = jdbcTemplateVss.queryForList("select table_name,file_name from data_table  where status=1 and tb_type=1");
            for (Map<String, Object> map : dataTable) {
                String tabName = map.get("TABLE_NAME").toString();
                String fileName = map.get("FILE_NAME").toString();
                if (!tabName.isEmpty()) {
                    try {
                        //String colStr = MultiDBUtils.get("VSS").getJdbcTemplate().queryForObject("select  wm_concat(case when data_type='DATE' then 'CONVERT(varchar(8),'||column_name||',112)+replace(CONVERT(varchar(8),'||column_name||',114),'':'','''') '||column_name else column_name end ) colstr from dba_tab_columns where table_name=? and owner='BHGVSS' and column_name not in ('RCV_STATUS','RCV_DATE') order by column_id asc", new Object[]{tabName}, String.class);
                        List<Map<String, Object>> colList = jdbcTemplateVss.queryForList(String.format("select column_name, c.DATA_TYPE\n" +
                                "  from dba_tab_columns c\n" +
                                " where table_name = '%s' \n" +
                                "   and owner = 'BHGVSS'\n" +
                                "   and column_name not in ('RCV_STATUS', 'RCV_DATE')\n" +
                                " order by column_id asc", tabName));
                        String select = "";
                        for (int i = 0; i < colList.size(); i++) {
                            if (i > 0) {
                                select += ",";
                            }
                            String colName = colList.get(i).get("COLUMN_NAME").toString();
                            String colDataType = colList.get(i).get("DATA_TYPE").toString();
                            if (colDataType.equals("DATE")) {
                                select += String.format("CONVERT(varchar(8),%s,112)+replace(CONVERT(varchar(8),%s,114),':','') %s", colName, colName, colName);
                            } else {
                                select += colName;
                            }
                        }
                        String sql = "select " + select + " from " + tabName + " where RCV_STATUS=2";
                        jdbcTemplate.update(String.format("update %s  set RCV_STATUS=2 where (RCV_STATUS=0 or RCV_STATUS is null) ", tabName));
                        List<Map<String, Object>> listRow = jdbcTemplate.queryForList(sql);
                        String filePath = rcvPath + fileName + DateUtils.getDate("yyyyMMddHHmmss")+".tmp";
                        String filePathNew = rcvPath + fileName + DateUtils.getDate("yyyyMMddHHmmss")+".dat";
                        for (int i = 0; i < listRow.size(); i++) {
                            int colInx = 0;
                            StringBuilder sb = new StringBuilder();
                            for (Map<String, Object> k : colList) {
                                if (colInx > 0) {
                                    sb.append("|");
                                }
                                try {
                                    if(listRow.get(i).get(k.get("COLUMN_NAME"))!=null)
                                    {
                                        String value=listRow.get(i).get(k.get("COLUMN_NAME")).toString().replaceAll("\r|\n","");
                                        sb.append( value== null ? "" : value);
                                    }
                                    else {
                                        sb.append("");
                                    }
                                }
                                catch (Exception e){
                                    logger.info(String.format("【%s】第{%s}数据错误!", tabName,colInx));
                                }
                                colInx++;
                            }
                            sb.append("\r\n");
                            FileUtils.writeToFile(filePath, sb.toString(), "GBK", true);

                        }
                        if (listRow.size() > 0) {
                            FileUtils.writeToFile(filePath, String.format("END|%s|%s", listRow.size(), DateUtils.getDate("yyyyMMdd")), "GBK", true);
                            if(new File(filePath).exists()){

                                new File(filePath).renameTo(new File(filePathNew));
                            }
                            jdbcTemplate.update(String.format("update %s  set RCV_STATUS=1,RCV_DATE=GETDATE()  where RCV_STATUS=2", tabName));
                            logger.info(String.format("【%s】数据文件己生成完成,共计【%s】条记录!", tabName,listRow.size()));
                        } else {
                            logger.error(String.format("【%s】数据为空,生成失败!", tabName));
                        }

                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }
}
